<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="names" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="ages" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sexs">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="moveFn(item.id)">删除</button>
            <button @click="bao(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      names: "",
      ages: "",
      sexs: "男",
      isAll: false,
      sums: "",
      list: JSON.parse(localStorage.getItem("todoss")) || [
        {
          id: 10,
          name: "xm",
          age: 10,
          sex: "男",
        },
        {
          id: 11,
          name: "xh",
          age: 11,
          sex: "女",
        },
        {
          id: 12,
          name: "xhua",
          age: 12,
          sex: "男",
        },
      ],
    };
  },
  methods: {
    addFn() {
      if (this.names === "" || this.ages === "") {
        return alert("请输入完整信息");
      }
      if (this.isAll === false) {
        this.list.unshift({
          id: +new Date(),
          name: this.names,
          age: this.ages,
          sex: this.sexs,
        });
      } else {
        this.sums.name = this.names;
        this.sums.age = this.ages;
        this.sums.sex = this.sexs;
      }
      this.names = "";
      this.ages = "";
      this.sexs = "男";
    },
    moveFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    bao(id) {
      const sum = this.list.find((item) => item.id === id);
      //   console.log(sum);
      (this.sums = sum),
        (this.names = sum.name),
        (this.ages = sum.age),
        (this.sexs = sum.sex);

      this.isAll = true;
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("todoss", JSON.stringify(this.list));
      },
    },
  },
};
</script>
